package com.example.luke.shengdangxiaoattendance.Handler;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;

import com.example.luke.shengdangxiaoattendance.Common.MainApp;
import com.example.luke.shengdangxiaoattendance.MainActivity;
import com.example.luke.shengdangxiaoattendance.Model.App;
import com.example.luke.shengdangxiaoattendance.Model.Setting;
import com.example.luke.shengdangxiaoattendance.Service.AppService;
import com.example.luke.shengdangxiaoattendance.Util.GlobalFunction;

/**
 * Created by luke on 31/08/2017.
 */

public class UnCeHandler implements   Thread.UncaughtExceptionHandler{

    private Thread.UncaughtExceptionHandler mDefaultHandler;
    public static final String TAG = "CatchExcep";
   private MainApp application;
    Intent serviceIntent;

    public UnCeHandler(MainApp application){
        //获取系统默认的UncaughtException处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        this.application = application;
        startService();


    }

    private void startService(){


        serviceIntent=new Intent(application.getApplicationContext(),AppService.class);
         application.startService(serviceIntent);


        LocalBroadcastManager.getInstance(application).registerReceiver(receiver(),new IntentFilter("custom-message"));
    }

    private BroadcastReceiver receiver(){
        return new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {



            boolean stat=Setting.allowLoop(application.getApplicationContext());
              //  GlobalFunction.printTextByTag("tag"+stat);


            //application.getBaseContext().getPackageManager().getLaunchIntentForPackage()

                if (stat){
                  //  GlobalFunction.printTextByTag("dd:"+stat);

                  restartApp();


                }

                application.stopService(serviceIntent);
               // }

            }
        };

    }
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if(!handleException(ex) && mDefaultHandler != null){
            GlobalFunction.printTextByTag("vvd");
            //如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        }else{

            restartApp();

        }
    }

    boolean temp=true;

    private void restartApp(){

      //  if (Setting.allowAppRestart(application.getApplicationContext())){

            //Setting.saveAppRestartMark(application.getApplicationContext(),false);

          GlobalFunction.printTextByTag("restart app");
            Intent intent = new Intent(application.getApplicationContext(),MainActivity.class);
            PendingIntent restartIntent = PendingIntent.getActivity(
                    application, 0, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            //退出程序
            AlarmManager mgr = (AlarmManager)application.getSystemService(Context.ALARM_SERVICE);
            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100,
                    restartIntent); // 1秒钟后重启应用
            application.finishActivity();
            System.exit(0);
         //   Thread.setDefaultUncaughtExceptionHandler(null);
       //     temp=false;

//          }

    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        //使用Toast来显示异常信息
//        new Thread(){
//            @Override
//            public void run() {
//                Looper.prepare();
//                Toast.makeText(application.getApplicationContext(), "很抱歉,程序出现异常,即将退出.",
//                        Toast.LENGTH_SHORT).show();
//                Looper.loop();
//            }
//        }.start();
        return true;
    }
}